package com.lili.setting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lili.model.setting.Department;
import com.lili.model.setting.DepartmentRole;
import com.lili.setting.mapper.DepartmentMapper;
import com.lili.setting.mapper.DepartmentRoleMapper;
import com.lili.setting.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@SuppressWarnings("all")
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DepartmentRoleMapper departmentRoleMapper;

    @Override
    public void saveDept(Department department) {
        departmentMapper.insert(department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 开启事务
    public void saveRoleDept(DepartmentRole departmentRole) {
        // 获取部门 id
        String departmentId = departmentRole.getDepartmentId();

        // 根据部门id 先删除部门权限表中的数据
        QueryWrapper<DepartmentRole> wrapper = new QueryWrapper<>();
        wrapper.eq("department_id", departmentId);
        // 删除当前部门所拥有的的所有权限
        departmentRoleMapper.delete(wrapper);
        // 保存当前部门的权限
        String[] split = departmentRole.getRoleId().split(",");
        if (null != split && split.length > 0) {
            // 遍历取出所有的roleId 进行插入操作
            for (String roleId : split) {
                departmentRole.setRoleId(roleId);
                departmentRoleMapper.insert(departmentRole);
            }
        }
    }

    /**
     * 查询全部的部门信息
     * @return
     */
    @Override
    public List<Department> getList() {
        return departmentMapper.selectList(null);
    }
}
